package com.gton.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gton.config.common.ContextCommonMsg;
import com.gton.entity.AuthLoginUser;
import com.gton.mapper.AuthLoginUserMapper;
import com.gton.service.AuthLoginUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author GuoTong
 * @since 2022-11-27
 */
@Service
@Slf4j
public class AuthLoginUserServiceImpl extends ServiceImpl<AuthLoginUserMapper, AuthLoginUser> implements AuthLoginUserService {

    @Resource
    private AuthLoginUserMapper authLoginUserMapper;


    /**
     * Description: 查询用户登录
     *
     * @param name 用户名
     * @param pwd  密码
     * @author: GuoTong
     * @date: 2022-12-04 15:25:34
     * @return:cn.dev33.satoken.util.SaResult
     */
    @Override
    public SaResult queryUserNameAndPassword(String name, String pwd) {

        if (StringUtils.isAnyEmpty(name, pwd)) {
            log.error("username = {},password = {}", name, pwd);
            return SaResult.error(ContextCommonMsg.ERROR_MSG_5);
        }
        QueryWrapper<AuthLoginUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", name);
        queryWrapper.eq("password", pwd);
        List<AuthLoginUser> authLoginUsers = authLoginUserMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(authLoginUsers)) {
            return SaResult.error(ContextCommonMsg.ERROR_MSG_6);
        }
        StpUtil.login(authLoginUsers.get(0).getId());
        return SaResult.ok(ContextCommonMsg.SUCCESS_MSG_0).setData(StpUtil.getTokenValue());
    }


    /**
     * Description:  查询用户名是否已经被占用
     *
     * @param username 用户名
     * @author: GuoTong
     * @date: 2022-12-04 15:24:45
     * @return:boolean
     */
    @Override
    public boolean queryUserNameIsExist(String username) {
        if (StringUtils.isEmpty(username)) {
            return false;
        }
        QueryWrapper<AuthLoginUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<AuthLoginUser> authLoginUsers = authLoginUserMapper.selectList(queryWrapper);
        return CollectionUtils.isEmpty(authLoginUsers);
    }
}
